<template>
    <div>
        <el-form ref="formSearch" :model="formSearch" :rules="rules" label-width="100px" size="small" :inline="true">
            <el-form-item>
                <el-checkbox v-model="formSearch.checked">仅显示过期预警样品</el-checkbox>
            </el-form-item>
            <el-form-item label="处理状态:">
                <el-select v-model="formSearch.status" placeholder="处理状态" style="width:100px">
                    <el-option v-for="item in statusOption"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="样品分类:">
                <el-cascader v-model="formSearch.type"
                             :options="sampleTypeAllTreeSelect"
                             :props="{ expandTrigger: 'hover' }"
                             @change="handleSelectedType">
                </el-cascader>
                <!--            <el-select v-model="formSearch.type" placeholder="样品分类">-->
                <!--                <el-option v-for="item in sampleTypeOption"-->
                <!--                           :key="item.value"-->
                <!--                           :label="item.label"-->
                <!--                           :value="item.value">-->
                <!--                </el-option>-->
                <!--            </el-select>-->
            </el-form-item>
            <el-form-item label="留样时间:">
                <el-date-picker v-model="formSearch.date" type="daterange" range-separator="至" start-placeholder="开始日期"
                                end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="样品编码:">
                <el-input v-model="formSearch.code" placeholder="请输入样品编码"></el-input>
            </el-form-item>
            <el-form-item label="样品名称">
                <el-input v-model="formSearch.sampleName" placeholder="请输入样品名称"></el-input>
            </el-form-item>
            <el-form-item label="留样人">
                <el-input v-model="formSearch.people" placeholder="请输入样品留样人"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchFormSubmit">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <avue-crud :option="tableOption"
                   :data="gridData"
                   :table-loading="tableLoading"
                   :page="page"
                   @current-change='currentPage'
                   @size-change="sizeChange"
                   ref="crud">
            <template slot-scope="scope" slot="handleTime">{{ scope.row.isHandle === 0 ? '待处理' : '已处理' }} <span>/</span>
                {{ scope.row.endTime || '无' }}
            </template>
            <template slot-scope="scope" slot="editTime">{{ scope.row.updateName || '无' }}<span>/</span>{{
                scope.row.updateTime }}
            </template>
            <template slot-scope="scope" slot="sampleRetentionSave">{{ scope.row.warehouse }} <span>/</span> {{
                scope.row.sampleRetentionSave }}
            </template>
            <template slot-scope="scope" slot="status">{{ scope.row.status === 1 ? '未留样' : '已留样' }}</template>

            <template slot-scope="scope" slot="peopleAndTime">
                {{ scope.row.people ? scope.row.people : '无'}} <span>/</span>{{ scope.row.updateTime ?
                scope.row.updateTime : '无' }}
            </template>

            <template slot-scope="scope" slot="entrustUnit" v-if="scope.row.sample">
                {{ scope.row.sample.entrustUnit }} <span>/</span> {{ scope.row.sample.entrustUnitPhone }}
            </template>
            <template slot-scope="scope" slot="entrustPeople" v-if="scope.row.sample">
                {{ scope.row.people }} <span>/</span> {{ scope.row.sample.clientPhone }}
            </template>
            <template slot-scope="scope" slot="entrustAddress" v-if="scope.row.sample">{{ scope.row.sample.address }}
            </template>

            <template slot-scope="scope" slot="sampleName" v-if="scope.row.sample"> {{ scope.row.sample.name }}
            </template>
            <template slot-scope="scope" slot="code" v-if="scope.row.sample"> {{ scope.row.sample.code }}</template>
            <template slot-scope="scope" slot="specs" v-if="scope.row.sample"> {{ scope.row.sample.specs }}</template>
            <template slot-scope="scope" slot="menu">
                <el-button type="primary" size="small" plain @click.stop="handleEdit(scope.row,scope.index)">修改
                </el-button>
                <el-button type="primary" size="small" plain @click.stop="handleDelete(scope.row,scope.index)">删除
                </el-button>
                <el-button v-if="scope.row.isHandle == 0" type="primary" size="small" plain @click.stop="handleKeep(scope.row,scope.index)">处理
                </el-button>
                <!-- <el-button type="primary" size="small"  plain @click.stop="handleCancel(scope.row,scope.index)">撤销处理</el-button> -->
            </template>
        </avue-crud>

        <!-- 修改 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="30%">
            <el-form ref="dialogForm" :model="dialogForm" :rules="rules" label-position="right" label-width="130px">
                <el-form-item label="留样数量：" prop='numbers'>
                    <el-input v-model="dialogForm.numbers" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="留样人：" prop='people'>
                    <el-input v-model="dialogForm.people" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="留样时间：" prop="date">
                    <el-date-picker v-model="dialogForm.date" type="date" placeholder="选择日期"
                                    style="width:100%"></el-date-picker>
                </el-form-item>
                <el-form-item label="过期时间：" prop="overdueDate">
                    <el-date-picker v-model="dialogForm.overdueDate" type="date" placeholder="选择日期"
                                    style="width:100%"></el-date-picker>
                </el-form-item>
                <el-form-item label="过期预警(天)：" prop='warnTime'>
                    <el-input v-model="dialogForm.warnTime" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="储存仓库：" prop='warehouse'>
                    <el-select v-model="dialogForm.warehouse" placeholder="请选择" style="width:100%">
                        <el-option v-for="(item,index) in warehouseList"
                                   :key='index'
                                   :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="储存条件：" prop='condition'>
                    <el-select v-model="dialogForm.condition" placeholder="请选择" style="width:100%">
                        <el-option v-for="(item,index) in conditionList"
                                   :key='index'
                                   :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注：">
                    <el-input v-model="dialogForm.remarks" type="textarea" placeholder=""></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align:center">
                <el-button size="small" @click="dialogFormVisible = false">关 闭</el-button>
                <el-button size="small" type="primary" @click="handleAddLine('dialogForm')">确 认</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import moment from "moment"
    import {retainedOption} from "@/const-personal/sample/sampleList.js"
    import {validateAcquaintance} from "@/util/validate.js"
    import {getWarehouseTypes, getWarehouse} from '@/api/sysSetup/warehouse'
    import {
        DepartmentTreeVChildrenNull,
        getDepartmentTreeOfId
    } from "@/util/util.js"

    import {
        getSampleRetentionList,
        updateSampleRetention,
        getSampleRetentionDelete,
        handleSampleRetention,
        getSampleRetentionSaveList,
        findAllTypeSampleTypeList,
        getAllSampleTypeList
    } from "@/api/sample/sampleList.js"

    export default {
        name: "SamplesRetained",
        data() {
            return {
                tableOption: retainedOption, //表格数据
                statusOption: [
                    {value: '-1', label: '全部'},
                    {value: '0', label: '待处理'},
                    {value: '1', label: '已处理'}
                ], // 处理状态
                sampleTypeOption: [
                    {value: '-1', label: '全部'},
                    {value: '0', label: '未留样'},
                    {value: '1', label: '已留样'}
                ], //样品分类

                formSearch: {
                    checked: false,
                    status: '全部',
                    type: [{value: '-1', label: '全部'}],
                    date: [],
                    code: '',
                    sampleName: '',
                    people: ""
                },
                page: {
                    total: 10, //总页数
                    currentPage: 1, //当前页数
                    pageSize: 10, //每页显示多少条
                    pageSizes: [5, 10]
                },
                tableLoading: false,
                gridData: [{id: 0, status: 2}, {id: 2, status: 1}],//数据
                // 修改
                dialogTitle: '添加样品',
                dialogFormVisible: false,
                rules: {
                    warehouse: [{required: true, message: '请选择储存仓库', trigger: 'change'}],
                    condition: [{required: true, message: '请选择储存条件', trigger: 'change'}],
                    people: [{required: true, message: '请输入样品名字', trigger: 'blur'}],
                    numbers: [{required: true, validator: validateAcquaintance, trigger: 'blur'}],
                    warnTime: [{required: true, validator: validateAcquaintance, trigger: 'blur'}],
                    date: [{required: true, message: '请输入委托时间', trigger: 'change', type: 'date'}],
                    overdueDate: [{required: true, message: '请输入委托时间', trigger: 'change', type: 'date'}],
                },
                dialogForm: {
                    numbers: '',
                    people: '',
                    date: '',
                    overdueDate: '',
                    warnTime: '',
                    warehouse: '',
                    condition: '',
                    remarks: ''
                },
                warehouseList: [], //储存仓库
                conditionList: [], //储存条件
                sampleTypeList: [], //样品分类
                sampleTypeAllTreeSelect: [],
                sampleTypeAllTree: []
            }
        },
        methods: {
            // 搜索
            searchFormSubmit() {
                let sampType = this.formSearch.type
                const sampleTypeId = sampType.length > 1 ? sampType[sampType.length - 1] : sampType[0]

                const data = {
                    page: this.page.currentPage,
                    size: this.page.pageSize,
                    sampleRetention: {
                        isRetention: this.formSearch.status === '-1' ? '' : Number(this.formSearch.status),
                        sampleId: sampleTypeId === '-1' ? '' : sampleTypeId,
                        warning: this.formSearch.checked ? 1 : 0,
                        // status: this.formSearch.status,
                        endTime: this.formSearch.date.length ? moment(this.formSearch.date[1]).format('YYYY-MM-DD') : '',
                        startTime: this.formSearch.date.length ? moment(this.formSearch.date[0]).format('YYYY-MM-DD') : '',
                        // code: this.formSearch.code,
                        // sampleName: this.formSearch.sampleName,
                        people: this.formSearch.people || ''
                    }
                }
                console.log(data)
                getSampleRetentionList(data).then(res => {
                    if (res.data.code === 200) {
                        console.log(res)
                        this.gridData = res.data.data.list

                        const sampleInfo = getDepartmentTreeOfId(this.sampleTypeAllTreeSelect, item.sample.sampleTypeId)
                        item.sampleType = sampleInfo !== null ? sampleInfo.label : '无'

                        this.page.total = res.data.data.total;
                        this.page.currentPage = res.data.data.pageNum;
                        this.page.pageSize = res.data.data.pageSize;
                    }
                })
            },
            // 重置
            handleReset() {
                this.formSearch = {
                    checked: false,
                    status: '全部',
                    type: [{value: '-1', label: '全部'}],
                    date: [],
                    code: '',
                    sampleName: '',
                    people: ""
                }
            },
            // 切换页面
            currentPage(val) {
                console.log(val)
                this.page.currentPage = val
                this._getAllList()
            },
            sizeChange(val) {
                this.page.pageSize = val
                this._getAllList()
            },
            // 修改
            handleEdit(row, index) {
                this.dialogFormVisible = true
                this.dialogTitle = '样品留样'
                // const warehouseInfo = this.warehouseList.filter(item => item.value || item.label === this.dialogForm.warehouseId)
                // const conditionInfo = this.conditionList.filter(item => item.value || item.label === this.dialogForm.condition)
                this.dialogForm = {
                    id: row.id,
                    sampleId: row.sampleId,
                    numbers: row.numbers,
                    people: row.people,
                    date: new Date(row.startTime),
                    overdueDate: new Date(row.endTime),
                    warnTime: row.warning,
                    // warehouse: warehouseInfo.length > 0 ? warehouseInfo[0].label : '',
                    warehouse: row.warehouseId,
                    // condition: conditionInfo.length > 0 ? conditionInfo[0].label : '',
                    condition: row.sampleRetentionSaveId,
                    remarks: row.remarks
                }
                console.log(this.dialogForm)
            },
            // 删除
            handleDelete(row, index) {
                this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    getSampleRetentionDelete({id: row.id}).then(res => {
                        if (res.data.code == 200) {
                            this.$notify({title: '操作成功', type: 'success', message: '已成功删除!'});
                            this._getTableList()
                        } else {
                            this.$notify.error({title: '操作失败', message: res.data.message, type: 'danger',});
                        }
                    })
                }).catch(() => {
                    console.log("已取消删除")
                })
            },
            // 撤销处理
            handleCancel(row, index) {
            },
            // 处理
            handleKeep(row, index) {
                let that = this;
                that.$confirm('此操作将处理该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    //xxx
                    handleSampleRetention({id: row.id}).then(res => {
                        if (res.data.code == 200) {
                            that._getTableList()
                            that.$notify({title: '操作成功', type: 'success', message: '已成功处理!'});
                        } else {
                            that.$notify.error({title: '操作失败', message: res.data.message, type: 'danger',});
                        }
                    })
                }).catch(() => {
                    console.log("已取消处理");
                });
            },
            // 确认新增/修改
            handleAddLine(formName) {
                let that = this;
                that.$refs[formName].validate((valid) => {
                    if (valid) {
                        // const warehouseInfo = this.warehouseList.filter(item => item.label || item.value === this.dialogForm.warehouse)
                        // const conditionInfo = this.conditionList.filter(item => item.label || item.value === this.dialogForm.condition)
                        const data ={
                            sampleRetention :{
                                id: that.dialogForm.id,
                                numbers: Number(that.dialogForm.numbers),
                                people: that.dialogForm.people,
                                startTime: moment(that.dialogForm.date).format('YYYY-MM-DD'),
                                endTime: moment(that.dialogForm.overdueDate).format('YYYY-MM-DD'),
                                warning: Number(that.dialogForm.warnTime),
                                // warehouseId: warehouseInfo.length > 0 ? Number(warehouseInfo[0].value) : '',
                                warehouseId: that.dialogForm.warehouse,
                                // sampleRetentionSaveId: conditionInfo.length > 0 ? Number(conditionInfo[0].value) : '',
                                sampleRetentionSaveId: that.dialogForm.condition,
                                remarks: that.dialogForm.remarks,
                                sampleId: that.dialogForm.sampleId
                            }
                        }
                        updateSampleRetention(data).then(res => {
                            if (res.data.code === 200) {
                                that.$refs[formName].resetFields();
                                that.dialogFormVisible = false
                                that._getTableList()
                                that.$notify({title: '修改成功', type: 'success'})
                            } else {
                                that.$notify.error(res.data.message)
                            }
                        })
                    } else {
                        that.$notify.error({})
                    }
                })
            },
            handleSelectedType() {
            },
            // 获取样品分类
            _getSampleTypeList() {
                getAllSampleTypeList().then(res => {
                    if (res.data.code === 200) {
                        this.sampleTypeList = res.data.data
                        this.sampleTypeAllTreeSelect = DepartmentTreeVChildrenNull(res.data.data, [{
                            label: '全部',
                            value: '-1'
                        }])
                        this.sampleTypeAllTree = DepartmentTreeVChildrenNull(res.data.data)
                    }
                })
            },
            // 获取储存条件
            _getConditionList() {
                const data = {
                    page: this.page.currentPage,
                    size: this.page.pageSize
                }
                getSampleRetentionSaveList(data).then(res => {
                    if (res.data.code === 200) {
                        const result = res.data.data.list
                        let info = []
                        if (result.length) {
                            result.forEach(item => {
                                info.push({value: item.id, label: item.name})
                            })
                            this.conditionList = info
                        }
                    } else {
                        this.$notify.error(res.data.message)
                    }
                })
            },
            // 获取储存仓库
            _getWarehouseList() {
                const data = {
                    page: this.page.currentPage,
                    size: this.page.pageSize,
                    sampleRetention: {}
                }

                getWarehouse(data).then(res => {
                    if (res.data.code === 200) {
                        let result = res.data.data
                        let info = []
                        if (result.length) {
                            result.forEach(item => {
                                info.push({value: item.id, label: item.name})
                            })
                        }
                        this.warehouseList = info
                    } else {
                        this.$notify.error(res.data.message)
                    }
                })
            },
            // 获取表格列表
            _getTableList() {
                const data = {
                    page: this.page.currentPage,
                    size: this.page.pageSize,
                    sampleRetention: {}
                }

                getSampleRetentionList(data).then(res => {
                    if (res.data.code === 200) {
                        this.gridData = res.data.data.list

                        this.gridData.forEach(item => {
                            const sampleInfo = getDepartmentTreeOfId(this.sampleTypeAllTreeSelect, item.sample.sampleTypeId)
                            item.sampleType = sampleInfo !== null ? sampleInfo.label : '无'

                            const warehouseInfo = this.warehouseList.filter(ware => ware.value === item.warehouseId)
                            item.warehouse = warehouseInfo !== null ? warehouseInfo[0].label : ''

                            const conditionInfo = this.conditionList.filter(type => type.value === item.sampleRetentionSaveId)
                            item.sampleRetentionSave = conditionInfo.length > 0 ? conditionInfo[0].label : '无'

                            item.endTime = moment(item.endTime).format('YYYY-MM-DD')
                            item.updateTime = item.updateTime ? moment(item.updateTime).format('YYYY-MM-DD') : '无'
                        })

                        this.page.total = res.data.data.total
                        this.page.currentPage = res.data.data.pageNum
                        this.page.pageSize = res.data.data.pageSize
                    }
                })
            },
            // 样品分类、储存仓库、储存条件、表格数据
            _getAllList() {
                const data = {
                    page: this.page.currentPage,
                    size: this.page.pageSize
                }

                getAllSampleTypeList().then(res => {
                    if (res.data.code === 200) {
                        this.sampleTypeList = res.data.data
                        this.sampleTypeAllTreeSelect = DepartmentTreeVChildrenNull(res.data.data, [{
                            label: '全部',
                            value: '-1'
                        }])
                        this.sampleTypeAllTree = DepartmentTreeVChildrenNull(res.data.data)

                        getWarehouse(data).then(res => {
                            if (res.data.code === 200) {
                                let result = res.data.data
                                let data = []
                                if (result.length) {
                                    result.map(item => {
                                        data.push({value: item.id, label: item.name})
                                    })
                                    this.warehouseList = data
                                    this._getTableList() // 样品
                                }
                            } else {
                                this.$notify.error(res.data.message)
                            }
                        })
                    }
                })

                // this._getSampleTypeList()  // 样品分类

                // this._getWarehouseList(data)  // 储存仓库

                this._getConditionList()  // 留样储存条件
            }
        },
        created() {
            this._getAllList()

            // this._getSampleTypeList()  // 样品分类
            // this._getWarehouseList()  // 储存仓库
            // this._getConditionList()  // 留样储存条件
            // this._getTableList() // 样品
        }
    }
</script>

<style scoped></style>